package com.openness.example.lock;

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

import com.openness.crawler.lock.DistributedLock;
import com.openness.crawler.zookeeper.ZKConnectionLatch;


/**
 * @author Rain
 * @version 2013-5-21 上午10:50:01
 */

public class LockMain {

	private static class Counter {

		private int count = 0;

		private DistributedLock lock;

		public Counter(DistributedLock lock) {
			this.lock = lock;
		}

		public void increment() {
			lock.lock();

			try {
				int old = count;

				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
				}

				count++;

				System.out.println(Thread.currentThread().getName() + " "
						+ ((count - old) == 1 ? "true" : "false"));
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}

	}

	private static class CounterThread extends Thread {

		private Counter counter;

		public CounterThread(Counter counter) {
			this.counter = counter;
		}

		@Override
		public void run() {
			while (true) {
				try {
					counter.increment();
				} catch (Exception e) {

				} finally {
				}
			}
		}

	}

	public static void main(String[] args) throws IOException, KeeperException,
			InterruptedException {
		ZKConnectionLatch connectionLatch = new ZKConnectionLatch();
		
		ZooKeeper zk = new ZooKeeper("192.168.30.222:2181", 3000, connectionLatch);
		
		connectionLatch.await();

		if (zk.exists("/lock", false) == null) {
			zk.create("/lock", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
					CreateMode.PERSISTENT);
		}

		Counter counter = new Counter(new DistributedLock(zk, "/lock", "queue"));

		for (int i = 0; i < 5; i++) {
			new CounterThread(counter).start();
		}
	}
}
